package billing.svn;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import org.tmatesoft.svn.core.ISVNLogEntryHandler;
import org.tmatesoft.svn.core.SVNDepth;
import org.tmatesoft.svn.core.SVNException;
import org.tmatesoft.svn.core.SVNLogEntry;
import org.tmatesoft.svn.core.SVNNodeKind;
import org.tmatesoft.svn.core.wc.ISVNDiffStatusHandler;
import org.tmatesoft.svn.core.wc.SVNDiffClient;
import org.tmatesoft.svn.core.wc.SVNDiffStatus;
import org.tmatesoft.svn.core.wc.SVNLogClient;
import org.tmatesoft.svn.core.wc.SVNRevision;
import org.tmatesoft.svn.core.wc.SVNStatusType;
import org.tmatesoft.svn.core.wc.SVNUpdateClient;

public class Context {
	static SVNConfig config = SVNConfig.getInstance();

	public static void main(String[] args) throws SVNException {
		// doLog(config.clientManager.getLogClient());
		List<SVNDiffStatus> diffLst = doDiff(config.clientManager.getDiffClient());
		doDiffSave(config.clientManager.getUpdateClient(),diffLst);
	}

	static void doDiffSave(SVNUpdateClient updateClient,
			List<SVNDiffStatus> diffLst) throws SVNException {
		String destinationDirectory = "F:/svntest/";
		for (SVNDiffStatus svnDiffStatus : diffLst) {
			File destination = new File(destinationDirectory + "\\" + svnDiffStatus.getPath());
			//updateClient.doExport(svnDiffStatus.getURL(), destination, this.endingRevision, this.endingRevision, null, true, SVNDepth.getInfinityOrEmptyDepth(true));
//			updateClient.doExport(svnDiffStatus.getURL(), destination, SVNRevision.PREVIOUS, SVNRevision.HEAD,false, true, SVNDepth.INFINITY);
			updateClient.doExport(svnDiffStatus.getURL(), destination, SVNRevision.create(66), SVNRevision.HEAD, "", false, SVNDepth.INFINITY);
		}
	}

	static List<SVNDiffStatus> doDiff(SVNDiffClient diffClient) throws SVNException {
		final List<SVNDiffStatus> result = new ArrayList<SVNDiffStatus>();
		ISVNDiffStatusHandler handler = new ISVNDiffStatusHandler() {
			@Override
			public void handleDiffStatus(SVNDiffStatus status)
					throws SVNException {
				if (status.getKind() == SVNNodeKind.FILE
						&& (status.getModificationType() == SVNStatusType.STATUS_ADDED || status
								.getModificationType() == SVNStatusType.STATUS_MODIFIED)) {
					result.add(status);
				}

			}
		};
		diffClient.doDiffStatus(config.svnUrl, SVNRevision.create(66),
				config.svnUrl, SVNRevision.HEAD, SVNDepth.INFINITY, false,
				handler);
		return result;

	}

	static void doLog(SVNLogClient logClient) throws SVNException {
		ISVNLogEntryHandler handle = new ISVNLogEntryHandler() {
			@Override
			public void handleLogEntry(SVNLogEntry entry) throws SVNException {
				System.out.println(entry.getDate());
			}
		};

		SVNRevision startRevision = SVNRevision.create(1);
		SVNRevision endRevision = SVNRevision.HEAD;

		logClient.doLog(config.svnUrl, new String[] {}, SVNRevision.HEAD,
				startRevision, endRevision, false, true, 100, handle);

	}
}
